<template>
  <div class="sku">
    <h3>iphone 13</h3>
    {{ processAttribute }}
    <hr />
    {{ processSkuMap }}
    <div v-for="(item, index) of processAttribute" :key="index">
      <div class="title" style="margin-bottom: 10px; margin-top: 10px">{{ item.title }}</div>
      <template v-for="(item1, index1) of item.values" :key="index1">
        <el-tag
          type="success"
          :class="[
            {
              active: item1.activity,
              disabled: item1.disabled,
            },
          ]"
          style="margin-right: 10px; cursor: pointer"
          @click="skuClickHandler(index, index1)"
          >{{ item1.attributeValue }}</el-tag
        >
      </template>
    </div>
    <div>当前选中的库存:{{ stock }}</div>
    <div>价格范围:{{ minPrice }}-{{ maxPrice }}</div>
  </div>
</template>

<script setup>
  import { onMounted } from 'vue';

  const skuAttribute = ref([
    {
      id: 1,
      title: '颜色',
      values: [{ attributeValue: '红色' }, { attributeValue: '绿色' }],
    },
    {
      id: 2,
      title: '大小',
      values: [{ attributeValue: 'S' }, { attributeValue: 'M' }],
    },
  ]);
  const skuList = ref([
    {
      attributeValue: '红色,S',
      thumbnailUrl: '',
      params: [{ name: '大小', value: 'S' }],
      id: '',
      price: '10',
      stock: '0',
    },
    {
      attributeValue: '红色,M',
      thumbnailUrl: '',
      params: [{ name: '大小', value: 'S' }],
      id: '',
      price: '20',
      stock: '10',
    },
    {
      attributeValue: '绿色,S',
      thumbnailUrl: '',
      params: [{ name: '大小', value: 'S' }],
      id: '',
      price: '30',
      stock: '20',
    },
    {
      attributeValue: '绿色,M',
      thumbnailUrl: '',
      params: [{ name: '大小', value: 'S' }],
      id: '',
      price: '40',
      stock: '0',
    },
  ]);
  const processAttribute = ref([]);
  const processSkuMap = ref({});
  const initData = () => {
    for (const item of skuAttribute.value) {
      let temp = {
        id: item.id,
        title: item.title,
      };
      temp.values = item.values.map((it) => {
        return {
          ...it,
          activity: false,
          disabled: itemquantity(it.attributeValue) <= 0, // 判断当前是否小于0的库存
          stock: itemquantity(it.attributeValue),
        };
      });
      processAttribute.value.push(temp);
    }
    // 对 skuList 数据进行加工，并存入 processSkuMap 中
    for (const item of skuList.value) {
      let combArr = arrayCombine(item.attributeValue.split(','));
      for (let j = 0; j < combArr.length; j++) {
        var key = combArr[j].join(',');
        if (processSkuMap.value[key]) {
          // 库存累加，价格添加进数组
          processSkuMap.value[key].stock += +item.stock;
          processSkuMap.value[key].prices.push(item.price);
        } else {
          processSkuMap.value[key] = {
            stock: +item.stock,
            prices: [item.price],
          };
        }
      }
    }
    // 计算下
    // skuCheck();
  };
  // 计算当前sku的库存
  const itemquantity = (item) => {
    let quantity = 0;
    skuList.value.forEach((element) => {
      var skuArr = element.attributeValue.split(',');
      if (skuArr.indexOf(item) != -1) {
        quantity += +element.stock;
      }
    });
    return quantity;
  };
  const arrayCombine = (targetArr) => {
    let resultArr = [];
    for (var n = 0; n <= targetArr.length; n++) {
      var flagArrs = getFlagArrs(targetArr.length, n);
      while (flagArrs.length) {
        var flagArr = flagArrs.shift();
        var combArr = Array(targetArr.length);
        for (var i = 0; i < targetArr.length; i++) {
          if (flagArr[i]) {
            combArr[i] = targetArr[i];
          }
        }
        resultArr.push(combArr);
      }
    }
    return resultArr;
  };

  const getFlagArrs = (m, n) => {
    let flagArrs = [];
    let flagArr = [];
    let isEnd = false;
    for (let i = 0; i < m; i++) {
      flagArr[i] = i < n ? 1 : 0;
    }
    flagArrs.push(flagArr.concat());
    // 当n不等于0并且m大于n的时候进入
    if (n && m > n) {
      while (!isEnd) {
        var leftCnt = 0;
        for (var i = 0; i < m - 1; i++) {
          if (flagArr[i] == 1 && flagArr[i + 1] == 0) {
            for (var j = 0; j < i; j++) {
              flagArr[j] = j < leftCnt ? 1 : 0;
            }
            flagArr[i] = 0;
            flagArr[i + 1] = 1;
            var aTmp = flagArr.concat();
            flagArrs.push(aTmp);
            if (aTmp.slice(-n).join('').indexOf('0') == -1) {
              isEnd = true;
            }
            break;
          }
          flagArr[i] == 1 && leftCnt++;
        }
      }
    }
    return flagArrs;
  };
  // 点击sku
  const skuClickHandler = (key1, key2) => {
    console.log(key1, key2, '点击了', processAttribute.value[key1]);
    // 如果不是被禁用的时候才执行
    if (!processAttribute.value[key1].values[key2].disabled) {
      // 选择和取消选中
      processAttribute.value[key1].values.map((item, index) => {
        item.activity = index == key2 ? !item.activity : false;
      });
      // 检查当前的sku是否有库存
      skuCheck();
      // 每次点击的时候判断禁用
      getStockPrice();
    }
  };
  // 当前选中的sku的库存机最小单价最大单价
  const stock = ref(0);
  const minPrice = ref(null);
  const maxPrice = ref(null);
  const skuCheck = () => {
    let sku = [];
    processAttribute.value.map((attr) => {
      let attributeValue = '';
      attr.values.map((item) => {
        console.log(item, '111');
        if (item.activity) {
          attributeValue = item.attributeValue;
        }
      });
      sku.push(attributeValue);
    });
    console.log(sku, '选中的的值', sku.join(','));
    stock.value = processSkuMap.value[sku.join(',')].stock;
    minPrice.value = Math.min.apply(Math, processSkuMap.value[sku.join(',')].prices);
    maxPrice.value = Math.max.apply(Math, processSkuMap.value[sku.join(',')].prices);
  };
  // 点击的时候判断库存禁用
  const getStockPrice = () => {
    processAttribute.value.map((attr) => {
      attr.values.map((item) => {
        item.disabled = itemquantity(item.attributeValue) <= 0;
      });
    });
    let count = 0;
    let i = 0;
    processAttribute.value.map((attr, index) => {
      let flag = false;
      attr.values.map((item) => {
        if (item.activity) {
          flag = true;
        }
      });
      if (!flag) {
        count += 1;
        i = index;
      }
    });
    // 当只有一组规格没选时
    if (count == 1) {
      processAttribute.value[i].values.map((item) => {
        let sku = [];
        let text = item.attributeValue;
        processAttribute.value.map((attr, index) => {
          if (index != i) {
            attr.values.map((item2) => {
              if (item2.activity) {
                sku.push(item2.attributeValue);
              }
            });
          } else {
            sku.push(text);
          }
        });
        if (processSkuMap.value[sku.join(',')].stock == 0) {
          item.disabled = true;
        }
      });
    }
    // 当所有规格都有选时
    if (count == 0) {
      processAttribute.value.map((attr, index) => {
        let i = index;
        processAttribute.value[index].values.map((item) => {
          if (!item.activity) {
            let sku = [];
            let text = item.attributeValue;
            processAttribute.value.map((list, index) => {
              if (index != i) {
                list.values.map((item2) => {
                  if (item2.activity) {
                    sku.push(item2.attributeValue);
                  }
                });
              } else {
                sku.push(text);
              }
            });
            if (processSkuMap.value[sku.join(',')].stock == 0) {
              item.disabled = true;
            }
          }
        });
      });
    }
  };
  onMounted(() => {
    initData();
  });
</script>

<style lang="scss" scoped>
  .sku {
    .active {
      background: skyblue;
      color: #fff;
      border: none;
    }
    .disabled {
      background: #ddd;
    }
  }
</style>
